<?php


namespace App\Common;


use EasySwoole\Component\Singleton;
use EasySwoole\HttpClient\HttpClient;

class HttpClients
{
    use Singleton;

    protected $headers = [
        'Accept ' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    ];

    /**
     * @param $url
     * @param array $data
     * @param string $method
     * @param array $cookie
     * @param array $headers
     * @return bool|mixed
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    public function http($url, $data = [], $method = "GET", $cookie = [], $headers = [])
    {
        $headers = empty($headers) ? $this->headers : $headers;
        $httpClient = new HttpClient($url);
        $httpClient->setHeaders($headers);
        if (!empty($cookie)) {
            foreach ($cookie as $k => $v) {
                $httpClient->addCookie($k, $v);
            }
        }
        switch (strtoupper($method)) {
            case 'POST':
                $response = $httpClient->post($data);
                break;
            case 'JSON':
                $response = $httpClient->postJson(json_encode($data,JSON_UNESCAPED_UNICODE));
                break;
            default:
                $response = $httpClient->get($data);
                break;
        }

        if ($response->getErrCode() == 0) {
            return $response->getBody();
        } else {
            return false;
        }
    }

    public function downloadFile($url, $fileName, $headers = [])
    {
//        $httpClient = new HttpClient($url);
//        if (empty($this->headers)) {
//            $httpClient->setHeaders($this->headers);
//        } else {
//            $httpClient->setHeaders($headers);
//        };
//        $response = $httpClient->download($fileName);
//        Coroutine::sleep(2);
//        return $response;
        $data = parse_url($url);
        if ($data['scheme']=='http') {
            $cli = new \Swoole\Coroutine\Http\Client($data['host'], 80);
        }elseif ($data['scheme']=='https'){
            $cli = new \Swoole\Coroutine\Http\Client($data['host'], 443, true);
        }
        $cli->set(['timeout' => 50]);
        $cli->setHeaders($headers);
        $cli->download($data['path'], $fileName);
        echo $data['host'], $data['path'], ' => ', $fileName, PHP_EOL;
    }
}
